package cn.hicard.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import cn.hicard.common.Constant;

/**
 * 应用程序配置文件分析类
 * @author zhangy
 *
 */
public class AppConfig {
	/** 日志工具 */
	private static Logger logger = Logger.getLogger(Constant.LOG_FRAME);
	/** 配置项的key,value映射map */
	private static HashMap<String, String> configs = new HashMap<String, String>();
	/** 默认的配置文件 */
	public final static String DEFAULT_FILE = "/configuration.xml";
	
	static{
		// 加载默认的配置文件
		load(DEFAULT_FILE);
	}
	
	/**
	 * 加载指定的配置文件
	 * @param filename
	 */
	public static void load(String filename){
		logger.debug("开始加载配置文件[" + filename + "]……");
		StringBuffer xml = new StringBuffer();
		InputStream is = AppConfig.class.getResourceAsStream(filename);
		BufferedReader reader = null;
		String line = null;
		try {
			reader = new BufferedReader(new InputStreamReader(is, "GB18030"));
			while((line = reader.readLine()) != null){
				xml.append(line);
			}
			Document doc = DocumentHelper.parseText(xml.toString());
			Element root = doc.getRootElement();
			
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			// 保证在任何时候调用load方法时都能完重新加载配置
			configs = new HashMap<String, String>();
			for (Element lmt : list) {
				String key = lmt.attributeValue("key");				
				String attrValue = lmt.attributeValue("value");
				String txtValue = lmt.getText();
				
				// 优先使用不为null和长度大于0的，其次以attValue优先
				if(attrValue != null && attrValue.length()>0){
					configs.put(key, attrValue);
				}else{
					configs.put(key, txtValue);
				}				
			}
			logger.info("加载配置文件["+filename+"]成功！");
		} catch (Exception e) {
			logger.error("加载配置文件["+filename+"]出错", e);
		} finally {
			try {
				reader.close();
			} catch (Exception e2) {
			}
		}
	}


	/**
	 * 取得配置值
	 * @param key
	 * @return
	 */
	public static String get(String key){
		return configs.get(key);
	}
}
